/*
        Firesoft 
        
    Copyright (C) 2010, Arttu Viljakainen 
    Published under GNU General Public License V3 
    (see http://www.gnu.org/licenses/licenses.html)
    
    This file is part of Firesoft.

    Firesoft is free software: 
    you can redistribute it and/or modify it under the terms of the GNU General 
    Public License as published by the Free Software Foundation, 
    either version 3 of the License, or (at your option) any later version.

    Firesoft is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General 
    Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Tool for Path Finding Algorithm Testing. If not, see         
    <http://www.gnu.org/licenses/>.
 */
package softstarter.gui.subareas;

import java.io.File;

import softstarter.filehandling.FileCentre;
import softstarter.filehandling.search.SearchEngine;
import softstarter.gui.master.GUIStateController;
import softstarter.launching.ActionPerformer;

public class FireActionsController implements FireActionsInterface {

    private GUIStateController controller;
	private FileCentre fileCentre;
	private SearchEngine searchEngine;
	private ActionPerformer actionPerformer;
		
	public FireActionsController(GUIStateController controller) {
	    this.controller = controller;
		fileCentre = FileCentre.getInstance();
		searchEngine = SearchEngine.getInstance();
		actionPerformer = new ActionPerformer();
	}
	
	@Override
	public void updateTopHitsListToCommandLine(String lastCharFromListener) {
		controller.getCommandLine().populateCommandLineAndShowPopup(searchEngine.getTopHits(fileCentre.getFiles(), controller.getCommandLine().getSearchWord() + lastCharFromListener, 10));
	}

	@Override
	public boolean startSoftware() {
	    
	    String firstCandidate = controller.getCommandLine().getFirstLaunchCandidate();
	    String secondCandidate = controller.getCommandLine().getSecondLaunchCandidate();
	    
        boolean clearTheCommandlineAfterTryingToExecuteAFile = false;
        
        if(isThereAFileInThePath(firstCandidate)) {
            actionPerformer.performActionFor(firstCandidate);
            clearTheCommandlineAfterTryingToExecuteAFile = true;
        } else if(isThereAFileInThePath(secondCandidate)) {
            actionPerformer.performActionFor(secondCandidate);
            clearTheCommandlineAfterTryingToExecuteAFile = true;
        }

        if(clearTheCommandlineAfterTryingToExecuteAFile) {
            controller.clearCommandlineAndHideWindow();
            return true;
        }
        
        return false;
	}
	
	private boolean isThereAFileInThePath(String path) {
	    File file = new File(path);
	    return file.exists();	    
	}
}
